<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Activation\Contributor\Collection;

use SplObjectStorage;
use Slipstream\Infrastructure\Context\ScopeAnalyzerInterface;
use Slipstream\Configuration\Context\WalkerInterface;
use Slipstream\Activation\SessionInterface;

/**
 * 
 * 
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class WalkerCollectorContributor extends AbstractCollectorContributor
{
	/**
	 * @var WalkerInterface
	 */
	protected $contextWalker;
	
	/**
	 * @var ScopeAnalyzerInterface
	 */
	protected $scopeAnalyzer;
	
	/**
	 * Class constructor
	 *
	 * @param WalkerInterface $contextWalker
	 * @param ScopeAnalyzerInterface $scopeAnalyzer
	 * @return void
	 */
	public function __construct(WalkerInterface $contextWalker, ScopeAnalyzerInterface $scopeAnalyzer)
	{
		$this->contextWalker = $contextWalker;
		$this->scopeAnalyzer = $scopeAnalyzer;
	}
	
	/**
	 * Called during an activation session so it can be contributed to
	 * 
	 * @param SessionInterface $session
	 * @return void
	 */
	public function onActivation(SessionInterface $session)
	{
		$targetContext = $session->getTargetContext();
		
		// Configure the infrastructure components
		$this->contextWalker->setTargetContext($targetContext);
		$this->scopeAnalyzer->setTargetContext($targetContext);
		
		// Collect policies from each context in the tree
		$collectedPolicies = new SplObjectStorage();
		do {
			$context = $this->contextWalker->getContext();
			$policies = $context->getPolicies();
			foreach($policies as $policy) {
				// Filter out policies that aren't in the scope of the target context
				if($this->scopeAnalyzer->isInScope($policy, $context)) {
					$collectedPolicies->attach($policy);
				}
			}
		} while($this->contextWalker->next());
		
		// Add collected policies to the activation session
		$session->addPolicies($collectedPolicies);
	}
}